from PyModuleCommModule import PyModuleComm
import modulecommpython
import numpy as np  
import time
import sys 
import cv2
from queue import Queue

import proto.cameraobjectarray_pb2 as cameraobjectarray_pb2
import proto.rawpic_pb2 as rawpic_pb2

from vehiclecount import VehicleCount

time_objectarray = 0
msg_cameraobjectarray = cameraobjectarray_pb2.cameraobjectarray()

msg_rawpic = rawpic_pb2.rawpic()
time_rawpic = 0
pic_mat = None
pic_queue = Queue(3)

def cameraobjectarray_callback(arr : np,nsize,time):
    global msg_cameraobjectarray
    global time_objectarray
    sub_arr = arr[0:nsize]
    databytes = sub_arr.tobytes() #sub_arr.tostring()
    msg = cameraobjectarray_pb2.cameraobjectarray()
    msg.ParseFromString(databytes)
    msg_cameraobjectarray = msg
    time_objectarray = time
    length = len(msg_cameraobjectarray.obj)
    #print("obj size: ",length)
    pass


def rawpic_callback(arr : np,nsize,time):
    global msg_rawpic
    global time_rawpic
    global pic_mat
    sub_arr = arr[0:nsize]
    databytes = sub_arr.tobytes() #sub_arr.tostring()
    msg = rawpic_pb2.rawpic()
    msg.ParseFromString(databytes)
    msg_rawpic = msg
    time_rawpic = time
    mat = np.zeros((msg_rawpic.height,msg_rawpic.width,3),dtype=np.uint8)
    buff = np.frombuffer(msg_rawpic.picdata,dtype=np.uint8)
    mat = cv2.imdecode(buff,cv2.IMREAD_COLOR)
    # pic_mat = mat
    pic_queue.put(mat)
    pass


if __name__ == "__main__":  
    # 初始化一个变量  
    count = 0
    count = 3.5/1.5
    count = int(count)
    print("count = ",count)  

    mobj = PyModuleComm("vision_objectarray")
    mobj.RegisterRecv(cameraobjectarray_callback)

    mpic = PyModuleComm("vision_objectimage")
    mpic.RegisterRecv(rawpic_callback)


    # 定义识别线线的起点和终点坐标
    line_start = np.array([150, 480])  # 起点
    line_end = np.array([900, 480])  # 终点
    max_track_length = 30  # 最大轨迹长度
    unupdated_timeout = 0.1  # 未更新的轨迹存在时间（秒）
    identification_range = 30  # 连续框判断误差（像素）
    calculate_range_flag = True

    counter = VehicleCount(line_start,line_end,max_track_length,unupdated_timeout,
                           calculate_range_flag,identification_range)
    
    # 使用while循环，只要count小于10，就继续循环  
    cv2.namedWindow("pic",cv2.WINDOW_NORMAL)
    while count < 10:
        #MakeDecision(md,msg_cameraobjectarray)
        # if pic_mat is not None:
        if not pic_queue.empty():
            pic_mat = pic_queue.get()
            counter.count(msg_cameraobjectarray,pic_mat)
            cv2.imshow("pic",pic_mat)
            if cv2.waitKey(1) & 0xFF == ord("q"):
            	# gai
               img = pic_mat
               #gai
               cv2.imwrite('img_c.jpg', pic_mat)  # 存储为图像
               break
    cv2.destroyAllWindows()
    
    #zhenggefuzhizhantie
    def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
        if event == cv2.EVENT_LBUTTONDOWN:
            xy = "%d,%d" % (x, y)
            cv2.circle(img, (x, y), 1, (255, 0, 0), thickness=-1)
            print((x,y))
            cv2.putText(img, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,
                        1.5, (255, 255, 255), thickness=2)
            cv2.imshow("image", img)

    cv2.namedWindow("image", cv2.WINDOW_AUTOSIZE)
    cv2.setMouseCallback("image", on_EVENT_LBUTTONDOWN)
    cv2.imshow("image", img)

    while (True):
        try:
            if cv2.waitKey(10) & 0xFF == ord('q'):
                break
        except Exception:
            cv2.destroyWindow("image")
            break

    print("循环结束！")  

